package com.itheima.health.controller;

import com.alibaba.dubbo.config.annotation.Reference;
import com.itheima.health.constant.MessageConstant;
import com.itheima.health.constant.RedisMessageConstant;
import com.itheima.health.entity.Result;
import com.itheima.health.pojo.User;
import com.itheima.health.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import redis.clients.jedis.JedisPool;

import java.util.Map;

/**
 * @ClassName SetmealMobileController
 * @Description TODO
 * @Author ly
 * @Company 深圳黑马程序员
 * @Date 2019/8/27 10:02
 * @Version V1.0
 */
@RestController
@RequestMapping(value = "/resetpassword")
public class ResetPasswordController {

    @Reference
    UserService userService;

    @Autowired
    JedisPool jedisPool;

    // 修改密码前的身份认证
    @RequestMapping(value = "/identify")
    public Result identify(@RequestBody Map map){

        try {
            // 1. 判断验证码是否正确
            String validateCode = (String) map.get("validateCode");
            String redisCode = jedisPool.getResource().get(map.get("telephone") + RedisMessageConstant.SENDTYPE_RESETPWD);

            if(validateCode == null || !validateCode.equals(redisCode)){

                return new Result(false,MessageConstant.VALIDATECODE_ERROR);

            }

            User user = userService.findUserByTelephoneAndAccount(map);

            // 判断User是否为空
            if(user==null){
                return new Result(false,MessageConstant.IDENTIFY_FAIL);
            } else{
                return new Result(true,MessageConstant.IDENTIFY_SUCCESS,user);
            }
        } catch (Exception e) {
            e.printStackTrace();
            return new Result(false,MessageConstant.SYSTEM_ERROR);
        }
    }

    /**
     * 重置密码
     * @param map
     * @return
     */
    @RequestMapping(value = "/resetpw")
    public Result resetpw(@RequestBody Map map){
        try {

            if(map.get("account")==null || "".equals(map.get("account"))){

                return new Result(true,MessageConstant.RESETPW_FAIL);
            }


            userService.resetPasswordByUsername(map);
            // 如果修改成功
            return new Result(true,MessageConstant.RESETPW_SUCCESS);

        } catch (Exception e) {

            e.printStackTrace();
            // 如果修改密码失败
            return new Result(true,MessageConstant.RESETPW_FAIL);
        }
    }
}
